package com.lntea.netty.demo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOServer {
	private Selector selector;
	
	public void initServer(int port) throws IOException{
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.socket().bind(new InetSocketAddress(port));
		this.selector = Selector.open();
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
	}
	
	public void listen() throws IOException{
		System.out.println("����������ɹ���");
		while(true){
			selector.select();
			Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
			while(ite.hasNext()){
				SelectionKey key = ite.next();
				ite.remove();
				if(key.isAcceptable()){
					ServerSocketChannel channel = (ServerSocketChannel) key.channel();
					SocketChannel socket = channel.accept();
					socket.configureBlocking(false);
					socket.write(ByteBuffer.wrap(new String("hello world").getBytes()));
					socket.register(selector, SelectionKey.OP_READ);
				}else if(key.isReadable()){
					read(key);
				}
			}
		}
	}
	
	private void read(SelectionKey key) throws IOException {
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buffer = ByteBuffer.allocate(48);
		
		channel.read(buffer);
		byte[] data = buffer.array();
		String msg = new String(data).trim();
		System.out.println("server recieve msg:"+msg);
		
		ByteBuffer outBuffer = ByteBuffer.wrap(("server return:"+msg).getBytes());
		channel.write(outBuffer);
	}

	public static void main(String[] args) throws IOException {
		NIOServer nioServer = new NIOServer();
		nioServer.initServer(8000);
		nioServer.listen();
	}
}
